package com.soft.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    // 存储验证码（email -> code）
    private final Map<String, CodeInfo> codeCache = new ConcurrentHashMap<>();

    /**
     * 生成 6 位数字验证码
     */
    public String generateCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }

    /**
     * 发送验证码邮件并缓存
     */
    public void sendCode(String to) {
        String code = generateCode();

        // 缓存验证码，5分钟有效
        codeCache.put(to, new CodeInfo(code, System.currentTimeMillis() + 5 * 60 * 1000));

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2565929104@qq.com"); // 必须和 application.yml 配置一致
        message.setTo(to);
        message.setSubject("驴肉火烧大王注册/找回密码验证码");
        message.setText("您的验证码是：" + code + "，有效期 5 分钟，请勿泄露。");
        mailSender.send(message);
    }

    /**
     * 校验验证码
     */
    public boolean verifyCode(String email, String code) {
        CodeInfo codeInfo = codeCache.get(email);
        if (codeInfo == null) return false;

        // 检查过期
        if (System.currentTimeMillis() > codeInfo.expireTime) {
            codeCache.remove(email);
            return false;
        }

        // 检查是否匹配
        boolean success = codeInfo.code.equals(code);
        if (success) {
            codeCache.remove(email); // 验证成功后删除
        }
        return success;
    }

    // 内部类：验证码信息
    private static class CodeInfo {
        String code;
        long expireTime;

        CodeInfo(String code, long expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
    }
}
